package com.yanyu.space.common.im.handler;

import com.yanyu.space.common.im.support.ImRecer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author gz
 */
@Slf4j
@AllArgsConstructor
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
    private List<ImRecer> imRecers;

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        ChannelPipeline pipeline = sc.pipeline();
        pipeline.addLast(new HttpServerCodec())
                // 以块方式写数据
                .addLast(new ChunkedWriteHandler())
                /*
                 * 说明
                 * 1. http数据在传输过程中是分段, HttpObjectAggregator ，就是可以将多个段聚合
                 * 2. 这就是为什么，当浏览器发送大量数据时，就会发出多次http请求，就是为了让其聚合处理消息
                 */
                .addLast(new HttpObjectAggregator(1024 * 64))
                // 心跳检查
                .addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS))
                .addLast(new HeartBeatServerHandler())
                // websocket
                .addLast(new WebSocketServerProtocolHandler("/ws/space"))
                .addLast(new WebSocketFrameHandler(imRecers));
    }
}
